package com.taoyibao.hongcanting.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.taoyibao.hongcanting.BuildConfig;
import com.taoyibao.hongcanting.http.api.ApiService;
import com.taoyibao.hongcanting.http.converter.CustomGsonConverterFactory;
import com.taoyibao.hongcanting.http.converter.NobodyConverterFactory;
import com.taoyibao.hongcanting.http.interceptor.LoggingInterceptor;
import com.taoyibao.hongcanting.http.interceptor.MoreBaseUrlInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络请求
 */
public class JsonApiWrapper extends ApiWrapper {
    //服务器BaseURl
    private static String BASE_URL = BuildConfig.COMPANY_SERVER_ADD;
    private ApiService apiService;
    private static final JsonApiWrapper mInstance = new JsonApiWrapper();

    @Override
    protected void createOkClient() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new LoggingInterceptor())//打印日志
                .addInterceptor(new MoreBaseUrlInterceptor())//添加多个baseURL的切换拦截器
//                .addInterceptor(new ApiExceptionIntercept())//通信异常
//                .addInterceptor(new TokenInterceptor())//刷新token
//                .addInterceptor(new AddCookiesInterceptor(HongApplication.getContext())) //添加header 带cookies访问
//                .addInterceptor(new ReceivedCookiesInterceptor(HongApplication.getContext())) //保存服务器返回的cookies
                .sslSocketFactory(TrustSSLFactory.getSocketFactory()) //忽略证书
//                .hostnameVerifier(DO_NOT_VERIFY)//统一的BaseUrl时使用
                .build();
    }

    @Override
    protected void createRetrofit() {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(CustomGsonConverterFactory.create())  //设置json格式放宽时使用
                .addConverterFactory(NobodyConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();
    }

    @Override
    protected void createApi() {
        apiService = retrofit.create(ApiService.class);
    }

    public static ApiService getApiService() {
        return getInstance().apiService;
    }

    //获取单例
    public static JsonApiWrapper getInstance() {
        return mInstance;
    }
}
